#include "syntaxtreemodel.h"

SyntaxTreeModel::SyntaxTreeModel(QObject *parent)
	: QAbstractItemModel(parent)
	, m_SyntaxTree(NULL)
{

}

SyntaxTreeModel::SyntaxTreeModel(SyntaxTreeNode* root, QObject *parent)
	: QAbstractItemModel(parent)
	, m_SyntaxTree(root)
{

}

SyntaxTreeModel::~SyntaxTreeModel()
{
}

void SyntaxTreeModel::setRoot(SyntaxTreeNode *root)
{
	m_SyntaxTree = root;
}

int SyntaxTreeModel::rowCount(const QModelIndex &parent) const
{
	if(!parent.isValid())
	{
		if(m_SyntaxTree == NULL)
			return 0;
		else return 1;
	}

	return (static_cast<SyntaxTreeNode* >(parent.internalPointer()))->childrenCount();
}

int SyntaxTreeModel::columnCount(const QModelIndex &parent) const
{	
	return 1;
}

QModelIndex SyntaxTreeModel::index(int row, int column, const QModelIndex &parent) const
{
	//root
	if(!parent.isValid())
	{
		return createIndex(row, column, (void*)m_SyntaxTree);
	}
	//leaf
	if( (static_cast<SyntaxTreeNode* >(parent.internalPointer())->childrenCount() == 0))
	{
		return QModelIndex();
	}

	// gdzies w srodku drzewa
	return createIndex(row, column, ((static_cast<SyntaxTreeNode* >(parent.internalPointer()))->childAt(row)));
}

QModelIndex SyntaxTreeModel::parent(const QModelIndex &index) const
{	
	if(((static_cast<SyntaxTreeNode* >(index.internalPointer()))->parent() == NULL))
	{
		return QModelIndex();
	}
	SyntaxTreeNode* tmp = (static_cast<SyntaxTreeNode* >(index.internalPointer()));


	SyntaxTreeNode* grandparent = tmp->parent()->parent();
	qint32 row = 1000;

	if(grandparent == NULL)
	{
		return createIndex(0 ,0, m_SyntaxTree);
	}
	else
	{
		for(int i = 0; i < grandparent->childrenCount(); ++i)
		{
			if(tmp->parent() == grandparent->childAt(i))
			{
				row = i;
				i = grandparent->childrenCount();
			}
		}
		
		return createIndex(row ,0, tmp->parent());
	}
}


Qt::ItemFlags SyntaxTreeModel::flags(const QModelIndex &index) const
{
	return (Qt::ItemIsEnabled | Qt::ItemIsSelectable);
}

QVariant SyntaxTreeModel::headerData(int section, Qt::Orientation orientation, int role) const
{	
	return QVariant();
}

QVariant SyntaxTreeModel::data(const QModelIndex &index, int role) const
{
	SyntaxTreeNode* tmp = static_cast<SyntaxTreeNode* >(index.internalPointer());
	if(role == Qt::DisplayRole)
	{
		return (tmp->symbol()).value();
	}
	if(role == Qt::DecorationRole)
	{
		return QIcon(tr(":MyClass/Resources/dot.bmp"));
	}
	return QVariant();
}